package com.yulinlin.authorization.modules.admin.service;

import com.yulinlin.authorization.modules.AuthService;
import com.yulinlin.authorization.modules.admin.entity.SysUserDetailsDto;
import com.yulinlin.authorization.modules.admin.entity.SysUserEntity;
import com.yulinlin.data.core.model.BaseModelSelectWrapper;
import com.yulinlin.jdbc.session.JdbcSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component("admin")
public class AdminAuthService implements AuthService {



    @Autowired
    protected JdbcSession sqlSession;

    @Autowired
    private PasswordEncoder passwordEncoder;

    private UserDetails loadUser(SysUserEntity user){
        SysUserDetailsDto detailsDto =  new SysUserDetailsDto(user);
        SysUserDetailsDto dto =  sqlSession.getLazyProxy(detailsDto);

        List<SimpleGrantedAuthority> elements =  dto.getSysElementList().stream().map(
                row -> {
                    return new SimpleGrantedAuthority(row.getCode());
                }).collect(Collectors.toList());

        List<String> roles =  dto.getRoleList().stream().map(
                row -> {
                    return row.getCode();
                }).collect(Collectors.toList());

        UserDetails val  =   User.builder()
                .username(user.getId())
                .password(
                        passwordEncoder.encode(  user.getPassword())
                )
                .authorities(elements)


                .build();

        return val;

    }

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUserEntity user =  BaseModelSelectWrapper.newInstance(SysUserEntity.class)
                .eq("username",username)
                .selectOne();

        if(user != null){
            return loadUser(user);
        }else{
            throw new UsernameNotFoundException("用户名：" + username + " 不存在");
        }




    }

    @Override
    public UserDetails loadUserById(String id) throws UsernameNotFoundException {
        SysUserEntity user =  BaseModelSelectWrapper.newInstance(SysUserEntity.class)
                .eq("id",id)
                .selectOne();

        if(user != null){
            return loadUser(user);
        }else{
            throw new UsernameNotFoundException("用户id：" + id + " 不存在");
        }

    }
}
